<template>
	<div class="role-page">
		<el-alert type="info" :closable="false">
			<template #title>
				<div class="title-bar">
					<el-icon size="16"><ele-WarningFilled /></el-icon>
					<span>请完善角色信息&功能权限&数据权限进行保存操作！</span>
				</div>
			</template>
			<div>
				<el-button size="default" @click="handleCancel">取 消</el-button>
				<el-button size="default" type="primary" @click="handleSure" v-throttle>保 存</el-button>
			</div>
		</el-alert>
		<el-form ref="paramsFormRef" class="params-form w100" :inline="true" label-position="top" label-width="100px" :model="paramsForm" :rules="paramsRules">
			<el-row :gutter="10" class="mt10 w100">
				<el-col :span="6">
					<el-card class="box-card peak-dialog" shadow="never" style="height: 85vh">
						<template #header>
							<span class="card-main-title">角色信息</span>
						</template>
						<el-row :gutter="16" justify="start">
							<el-col :span="24">
								<el-form-item class="form-item" label="角色名称:" prop="roleName">
									<el-input v-model="paramsForm.roleName" placeholder="请输入角色名称" />
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item class="form-item" label="权限标识:" prop="roleKey">
									<el-input v-model="paramsForm.roleKey" placeholder="请输入权限标识" />
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item class="form-item" label="角色顺序:" prop="roleSort">
									<el-input-number v-model="paramsForm.roleSort" class="el-form-item" controls-position="right" :max="50" :min="1" placeholder="请输入角色顺序" :step-strictly="true" />
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item class="form-item" label="角色状态:" prop="status">
									<el-select v-model="paramsForm.status" class="el-form-item" placeholder="请选择用户角色">
										<el-option label="正常" value="0" />
										<el-option label="停用" value="1" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item class="form-item" label="备注信息:" prop="remark">
									<el-input v-model="paramsForm.remark" rows="3" type="textarea" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-card>
				</el-col>
				<el-col :span="9">
					<el-card class="box-card" shadow="never" style="height: 85vh">
						<template #header>
							<span class="card-main-title">功能权限</span>
						</template>
						<el-row>
							<el-col :span="24">
								<el-tree ref="pcTreeRef" @check="checkChange" default-expand-all :data="pcData" :check-strictly="true" node-key="id" show-checkbox class="menu-data-tree" />
							</el-col>
						</el-row>
					</el-card>
				</el-col>
				<el-col :span="9">
					<el-card class="box-card" shadow="never" style="height: 85vh">
						<template #header>
							<span class="card-main-title">数据权限</span>
						</template>
						<el-row>
							<el-col :span="24">
								<el-form-item class="form-item" label="权限范围:" prop="dataScope">
									<el-select v-model="paramsForm.dataScope" class="el-form-item" placeholder="请选择权限范围">
										<el-option label="所有数据权限" value="1" />
										<el-option label="自定义数据权限" value="2" />
										<el-option label="本部门数据权限" value="3" />
										<el-option label="本部门及以下数据权限" value="4" />
										<el-option label="仅本人数据权限" value="5" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="24" v-show="paramsForm.dataScope == '2'">
								<el-tree ref="scopeTreeRef" @check="checkChangeScope" default-expand-all :data="scoreTreeData" :check-strictly="true" node-key="id" show-checkbox class="menu-data-tree" />
							</el-col>
						</el-row>
					</el-card>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>
<script name="EditRoleComp" setup>
import global from '@/utils/global'
import mittBus from '@/utils/mitt'

/*
 *@Description: 状态初始化
 *@MethodAuthor: liuYuFeng
 *@Date: 2023-08-29 16:49:56
 */
const props = defineProps({
	action: {
		type: String,
		default: '',
	},
})

const route = useRoute()
// const router = useRouter()
const state = reactive({
	paramsFormRef: null,
	paramsForm: {
		roleId: '',
		roleName: '',
		roleSort: 0,
		status: '0',
		roleKey: '',
		remark: '',
		menuIds: [],
		deptIds: [],
		dataScope: '5',
	},
	paramsRules: {
		roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
		roleKey: [{ required: true, message: '请输入权限字符', trigger: 'blur' }],
	},
	pcData: [],
	pcTreeRef: null,
	// menuProps: {
	// 	children: 'children',
	// 	label: 'menuName',
	// },
	// deptProps: {
	// 	children: 'children',
	// 	label: 'deptName',
	// },
	scoreTreeData: [],
	scopeTreeRef: null,
})

const { paramsFormRef, paramsForm, paramsRules, pcData, pcTreeRef, scoreTreeData, scopeTreeRef } = toRefs(state)

/*
 *@Description: 生命周期
 *@MethodAuthor: liuYuFeng
 *@Date: 2023-08-29 16:50:35
 */
onMounted(async () => {
	await getScopeTreeData()
	await getPcTreeData()
})

/*
 *@Description: 方法模块
 *@MethodAuthor: liuYuFeng
 *@Date: 2023-08-29 16:50:47
 */
const getPcTreeData = () => {
	global.$fetchPostData(`/meta-system/web/v1/sysMenu/roleMenuTreeselectByRoleId`, {}).then(data => {
		if (data.code == 200) {
			state.pcData = data.data.menus
			if (props.action != 'add') {
				getDetailData(route.query.id)
			}
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
const getScopeTreeData = () => {
	global.$fetchPostData(`/meta-system/web/v1/sysRole/deptTreeByRoleId`, {}).then(data => {
		if (data.code == 200) {
			state.scoreTreeData = data.data.depts
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
//操作
// 关闭当前页面-返回列表页面
const handleCancel = () => {
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route, redirectUrl: '/system/role' }))
}
const handleSure = () => {
	const pcCheckeds = state.pcTreeRef.getCheckedKeys()
	const scopeCheckeds = state.scopeTreeRef.getCheckedKeys()
	state.paramsForm.menuIds = [...pcCheckeds]
	state.paramsForm.deptIds = [...scopeCheckeds]
	state.paramsFormRef.validate(valid => {
		if (valid) {
			if (props.action == 'add') {
				roleAddMethod()
			} else if (props.action == 'update') {
				roleUpdateMethod()
			} else if (props.action == 'copy') {
				state.paramsForm.roleId = null
				roleAddMethod()
			}
		} else {
			return false
		}
	})
}
// 新增
const roleAddMethod = () => {
	global.$fetchPostData(`/meta-system/web/v1/sysRole/add`, state.paramsForm).then(data => {
		if (data.code == 200) {
			global.$baseMessage(data.msg, 'success')
			handleCancel()
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
// 修改
const roleUpdateMethod = () => {
	global.$fetchPostData(`/meta-system/web/v1/sysRole/edit`, state.paramsForm).then(data => {
		if (data.code == 200) {
			global.$baseMessage(data.msg, 'success')
			handleCancel()
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
// 详情
const getDetailData = id => {
	global.$fetchPostData(`/meta-system/web/v1/sysRole/getInfo`, { idLong: id }).then(data => {
		if (data.code == 200) {
			state.paramsForm = data.data
			state.paramsForm.roleSort = Number(data.data.roleSort)
			state.pcTreeRef.setCheckedKeys(data.data.menuIds || [])
			state.scopeTreeRef.setCheckedKeys(data.data.deptIds || [])
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
/**
 * 选择子级默认选中父级，选中父级不选中子级
 * @param {*} data
 */
const checkChangeScope = data => {
	const node = state.scopeTreeRef.getNode(data.id)
	if (node.checked) {
		//如果当前是选中checkbox,则递归设置父节点和父父节点++选中
		setParentNode(node)
	} else {
		//当前是取消选中,将所有子节点都取消选中
		setChildenNode(node)
	}
}

const checkChange = data => {
	const node = state.pcTreeRef.getNode(data.id)
	if (node.checked) {
		//如果当前是选中checkbox,则递归设置父节点和父父节点++选中
		setParentNode(node)
	} else {
		//当前是取消选中,将所有子节点都取消选中
		setChildenNode(node)
	}
}
const setParentNode = node => {
	if (node.parent) {
		for (const key in node) {
			if (key === 'parent') {
				node[key].checked = true
				setParentNode(node[key])
			}
		}
	}
}
const setChildenNode = node => {
	const len = node.childNodes.length
	for (let i = 0; i < len; i++) {
		node.childNodes[i].checked = false
		setChildenNode(node.childNodes[i])
	}
}
// end
</script>
<style lang="scss" scoped>
.card-title {
	font-size: 16px;
}
.title-bar {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	span {
		padding-left: 3px;
		font-size: 14px;
	}
}
:deep() {
	.el-alert--info.is-light {
		padding: 5px 5px;
		background-color: #fff;
		border: 1px solid #fff;
	}
	.el-alert__content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}
}
.box-card {
	:deep() {
		.el-card__header {
			padding-left: 14px !important;
		}
		.el-card__body {
			height: 77vh;
			overflow-y: auto;
			overflow-x: hidden;
		}
	}
}
.detail-card {
	:deep() {
		.el-card__header {
			padding: 10px 14px !important;
		}
	}
}
</style>
